import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

import java.util.Arrays;

public class ShiroDemo {
    @Test
    public void testShiro(){
        // 1.创建一个基于ini文件的安全管理器工厂
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        // 2.从工厂中获取一个安全管理器
        SecurityManager manager = factory.getInstance();
        // 3.设置该安全管理器的运行环境
        SecurityUtils.setSecurityManager(manager);

        // 设置环境之后开始使用
        // 4.拿到一个主体,该主体默认是没有任何认证/授权信息
        Subject subject = SecurityUtils.getSubject();
        System.out.println("登录前:"+subject.isAuthenticated());
        // 5.认证操作(登录)
        // 准备一个用于登录的令牌
        UsernamePasswordToken token = new UsernamePasswordToken("admin","123");
        subject.login(token);
        // 6.查看认证状态
        System.out.println("登录后:"+subject.isAuthenticated());
        // UnknownAccountException 账户错误,不检查密码
        // IncorrectCredentialsException 账户正确,密码错误


        //==========================================================================
        System.out.println(subject.hasRole("role1"));
        System.out.println(Arrays.toString(subject.hasRoles(Arrays.asList("role1", "role2"))));// boolean[]
        System.out.println(subject.hasAllRoles(Arrays.asList("role1", "role2")));

        System.out.println(subject.isPermittedAll("user:delete","user:save","user:list"));
        System.out.println(subject.isPermitted("user:delete"));
        System.out.println(Arrays.toString(subject.isPermitted("user:delete","user:save")));
    }

}
